﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel;

using Seven.EntityBasic;
using Seven.Service;
using Seven.Service.Security;
using Seven.Site.Mvc;
using Seven.Site.Mvc.Attributes;
using Seven.Site.Models.ControllerActionModel;
using Seven.Tools.Helper;
using Seven.Tools.Extension;

namespace Seven.Site.Web.Controllers
{
    [CatchException(ActionType.数据)]
    public class PublicController : BaseController
    {
        #region 员工选择器

        /// <summary>
        /// 提供未创建用户的员工信息json数据
        /// </summary>
        /// <param name="companyId">所属公司ID</param>
        /// <param name="deptId">所属部门ID</param>
        /// <param name="positionId">所属岗位ID</param>
        /// <param name="realName">员工名字</param>
        /// <param name="page">页码</param>
        /// <param name="rows">每页条数</param>
        /// <param name="rangeFilter">是否根据管理范围过滤</param>
        /// <returns></returns>
        [Description("提供未创建用户的员工信息json数据")]
        [Login]
        public JsonResult StaffJsonForSelectorGrid(int? companyId, int? deptId, int? positionId, string realName, int? page, int? rows, bool rangeFilter = false)
        {
            int Page = page ?? 1;
            int Rows = rows ?? 10;

            return ServiceFactory.HrStaff.StaffGridForSelector(companyId, deptId, positionId, realName, Page, Rows, rangeFilter);
        }

        /// <summary>
        /// 提供已选员工信息json数据
        /// </summary>
        /// <param name="selected">已选id串</param>
        /// <returns></returns>
        [Description("提供已选员工信息json数据")]
        [Login]
        public JsonResult StaffJsonForSelectedGrid(string selected)
        {
            if (!string.IsNullOrWhiteSpace(selected))
            {
                return ServiceFactory.HrStaff.StaffGrid(selected);
            }
            else
            {
                return Json(new { total = 0, rows = new List<object>() });
            }
        }

        #endregion

        #region 角色选择器

        /// <summary>
        /// 提供指定公司的角色信息json数据
        /// </summary>
        /// <param name="companyId">公司ID</param>
        /// <param name="name">角色名称</param>
        /// <returns></returns>
        [Description("提供指定公司的角色信息json数据")]
        [Login]
        public JsonResult RoleJsonForSelectorGrid(int companyId, string name)
        {
            return ServiceFactory.SysRole.RoleGridForSelector(companyId, name);
        }

        #endregion

        #region 公用的获取菜单数据

        /// <summary>
        /// 获取根菜单json数据
        /// </summary>
        /// <param name="filter">是否根据用户范围过滤，默认是</param>
        /// <returns></returns>
        [Description("获取根菜单json数据")]
        [Login]
        public JsonResult GetRootMenusJson(bool filter = true)
        {
            if (filter)
            {
                var Menu = new Account().GetCurrentUserMenuRange(User.Identity.Name)
                    .Where(w => w.ParentID == 0 && w.IsShow)
                    .TryOrderBy(m => m.SortNumber)
                    .Select(s => new { s.ID, s.Name, s.IconCls, s.Code });

                return Json(Menu);
            }
            else
            {
                var Menu = new Account().GetCurrentUserMenuRange(User.Identity.Name)
                    .Where(w => w.ParentID == 0 && w.IsShow)
                    .TryOrderBy(m => m.SortNumber)
                    .Select(s => new { s.ID, s.Name, s.IconCls, s.Code });

                return Json(Menu);
            }
        }

        /// <summary>
        /// 根据根菜单信息获取后台菜单json数据
        /// </summary>
        /// <param name="parentId">根菜单ID</param>
        /// <param name="parentCode">根菜单Code</param>
        /// <returns></returns>
        [Description("根据根菜单信息获取后台菜单json数据")]
        [Login]
        public JsonResult GetChildrenMenusJson(int parentId, string parentCode)
        {
            var Result = new Account().GetCurrentUserMenuRange(User.Identity.Name).Where(w => w.ID != parentId && w.Code.StartsWith(parentCode)).OrderBy(o => o.SortNumber);

            return Json(Result.Select(s => new
            {
                id = s.ID,
                text = s.Name,
                iconCls = string.IsNullOrWhiteSpace(s.IconCls) ? SiteCore.DefaultIconClassName : s.IconCls,
                s.ParentID,
                attributes = new
                {
                    title = s.Name,
                    href = Tools.Helper.UrlHelper.GetRealUrl(s.ControllerName, s.ActionName),
                    iconCls = string.IsNullOrWhiteSpace(s.IconCls) ? SiteCore.DefaultIconClassName : s.IconCls
                }
            }));
        }

        /// <summary>
        /// 提供完整的菜单信息json数据
        /// </summary>
        /// <param name="showRoot">是否带“根目录”</param>
        /// <returns></returns>
        [Description("提供完整的菜单信息json数据")]
        [Login]
        public JsonResult FullMenusJson(bool showRoot = false)
        {
            return ServiceFactory.SysMenu.FullMenusJsonForTree(showRoot);
        }

        #endregion

        #region 公用的获取控制器、动作数据

        /// <summary>
        /// 提供控制器数据
        /// </summary>
        /// <returns></returns>
        [Description("提供控制器数据")]
        [Login]
        public JsonResult ControllerJson()
        {
            var ControllerList = ControllerActionGetter.GetControllersByAssembly(SiteCore.DefaultProjectAssemblyName);

            return Json(ControllerList.Select(s => new { id = s.ControllerName, text = s.ControllerName }));
        }

        /// <summary>
        /// 提供动作数据
        /// </summary>
        /// <param name="controllerName">控制器名称</param>
        /// <returns></returns>
        [Description("提供动作数据")]
        [Login]
        public JsonResult ActionJson(string controllerName)
        {
            var ActionList = new List<ActionModel>();
            if (!string.IsNullOrWhiteSpace(controllerName))
            {
                ActionList = ControllerActionGetter.GetActionsByAssembly(SiteCore.DefaultProjectAssemblyName, controllerName);
            }
            return Json(ActionList.Select(s => new { id = s.ActionName, text = s.ActionName + (s.IsViewPageAction ? "[页面]" : "[请求]"), attributes = new { s.IsViewPageAction, s.Description } }));
        }

        #endregion

        #region 公用的获取组织结构数据

        /// <summary>
        /// 以异步方式提供组织结构的json数据
        /// </summary>
        /// <param name="id">上级id</param>
        /// <param name="filter">是否根据管理范围过滤，默认过滤</param>
        /// <returns></returns>
        [Login]
        public JsonResult OrganizationJson(int id = 0, bool filter = true)
        {
            return ServiceFactory.HrOrganization.OrganizationJson(id, filter);
        }

        /// <summary>
        /// 提供公司的json数据
        /// </summary>
        /// <param name="filter">是否根据管理范围过滤，默认过滤</param>
        /// <returns></returns>
        [Login]
        public JsonResult CompanyJson(bool filter = true)
        {
            return ServiceFactory.HrOrganization.CompanyJson(filter);
        }

        /// <summary>
        /// 提供指定公司下的部门json数据
        /// </summary>
        /// <param name="companyId">指定公司ID</param>
        /// <param name="companyCode">指定公司Code</param>
        /// <param name="showSelf">是否显示自身数据，默认不显示</param>
        /// <param name="filter">是否根据管理范围过滤，默认过滤</param>
        /// <returns></returns>
        [Login]
        public JsonResult DeptJsonInSpecialCompanyID(int companyId, string companyCode, bool showSelf = false, bool filter = true)
        {
            return ServiceFactory.HrOrganization.DeptJsonInSpecialCompanyID(companyId, companyCode, showSelf, filter);
        }

        /// <summary>
        /// 以异步方式提供指定组织结构的json数据 (员工选择器中专用、比较特殊)
        /// </summary>
        /// <returns></returns>
        [Login]
        public JsonResult OrganizationJsonWithSelfForTree(int id = 0, int flag = 0)
        {
            var result = new List<object>();
            if (id == flag && id != 0)
            {
                var self = CurrentUserOrganRange.FirstOrDefault(f => f.ID == id);
                result.Add(new
                {
                    id = self.ID,
                    text = self.Type == OrganType.公司 ? self.ShortName : self.Name,
                    self.ParentID,
                    iconCls = SiteCore.GetOrganIcon(self.Type),
                    state = "open",
                    attributes = new
                    {
                        IsGroup = self.Type == OrganType.大集团,
                        IsSonGroup = self.Type == OrganType.子集团,
                        IsCompany = self.Type == OrganType.公司,
                        IsDept = self.Type == OrganType.部门
                    }
                });
            }
            var organs = CurrentUserOrganRange.Where(g => (g.ParentID == id));
            if (organs.Count() > 0) { organs = organs.OrderBy(o => o.SortNumber); }

            foreach (var item in organs)
            {
                result.Add(new
                {
                    id = item.ID,
                    text = item.Type == OrganType.公司 ? item.ShortName : item.Name,
                    item.ParentID,
                    iconCls = SiteCore.GetOrganIcon(item.Type),
                    state = item.Type == OrganType.大集团 ? "closed" : ((CurrentUserOrganRange.Any(a => a.ParentID == item.ID)) ? "closed" : "open"),
                    attributes = new
                    {
                        IsGroup = item.Type == OrganType.大集团,
                        IsSonGroup = item.Type == OrganType.子集团,
                        IsCompany = item.Type == OrganType.公司,
                        IsDept = item.Type == OrganType.部门
                    }
                });
            }

            return Json(result);
        }

        #endregion

        #region 公用的获取组织结构-用户数据

        /// <summary>
        /// 以异步方式提供组织结构-用户的json数据
        /// </summary>
        /// <param name="id">上级id</param>
        /// <param name="filter">是否根据管理范围过滤，默认过滤</param>
        /// <param name="includeCurrentUser">是否包含当前登录用户，默认不包含</param>
        /// <returns></returns>
        [Login]
        public JsonResult OrganizationUserJson(int id = 0, bool filter = true, bool includeCurrentUser = false)
        {
            return ServiceFactory.HrOrganization.OrganizationUserJson(id, filter, includeCurrentUser);
        }

        #endregion

        #region 公用的获取组织结构-角色数据

        /// <summary>
        /// 以异步方式提供组织结构-角色的json数据
        /// </summary>
        /// <param name="id">上级id</param>
        /// <param name="filter">是否根据管理范围过滤，默认过滤</param>
        /// <param name="includeCurrentRole">是否包含当前登录用户的角色，默认不包含</param>
        /// <returns></returns>
        [Login]
        public JsonResult OrganizationRoleJson(int id = 0, bool filter = true, bool includeCurrentRole = false)
        {
            return ServiceFactory.HrOrganization.OrganizationRoleJson(id, filter, includeCurrentRole);
        }

        #endregion
    }
}